package com.doctor.ui.medicalknowledge;

import java.io.File;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.TextView;

import com.doctor.adapter.KnowledgeFourthAdapter;
import com.doctor.bean.ArticleBean;
import com.doctor.bean.KnowledgeBean;
import com.doctor.comm.ConstConfig;
import com.doctor.comm.DialogHelper;
import com.doctor.comm.LoadingTip;
import com.doctor.comm.MyApplication;
import com.doctor.comm.DialogHelper.NoticeDialogCallback;
import com.doctor.comm.URLConfig;
import com.doctor.database.DES;
import com.doctor.database.DbOperator;
import com.doctor.database.DbOperator.DirAndArticleCallback;
import com.doctor.ui.BaseFragment;
import com.doctor.ui.R;

public class KnowledgeFourthFrag extends BaseFragment{

	/**
	 * 医学知识医疗技术四五级目录
	 */
	
	private Context context;
	private ExpandableListView listView;
	private KnowledgeFourthAdapter adapter;
	private TextView thirdName;
	private KnowledgeBean thirdBean;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		context=getActivity();
		thirdBean=(KnowledgeBean) getArguments().getSerializable(ConstConfig.BEAN);
		
		View view=inflater.inflate(R.layout.knowledge_fourth, container, false);
		initiaView(view);
		getData();
		
		return view;
	}
	
	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
		context=null;
		adapter=null;
		listView=null;
		thirdName=null;
		thirdBean=null;
	}
	
	@Override
	protected void initiaView(View view) {
		// TODO Auto-generated method stub
		thirdName=(TextView) view.findViewById(R.id.thirdDir);
		listView=(ExpandableListView) view.findViewById(R.id.listView);
	}
	
	@Override
	protected void getData() {
		// TODO Auto-generated method stub
		thirdName.setText(thirdBean.getDirname());
		LoadingTip.showDialog(context, getString(R.string.loading));
		
		new Thread() {
			public void run() {
				DbOperator.getInstance(context).selectDirAndArticle(thirdBean.getId(), new DirAndArticleCallback() {
					@Override
					public void onDirAndArticle(final int dirSize, final List<KnowledgeBean> dirList, final List<List<ArticleBean>> artList) {
						// TODO Auto-generated method stub
						listView.postDelayed(new Runnable() {
							@Override
							public void run() {
								// TODO Auto-generated method stub
								if (dirList.size() > 0 || artList.size() > 0) {
									adapter=new KnowledgeFourthAdapter(context, dirSize, dirList, artList);
									listView.setAdapter(adapter);
									listView.setOnChildClickListener(new OnChildClickListener() {			
										@Override
										public boolean onChildClick(ExpandableListView parent, View v,
												int groupPosition, int childPosition, long id) {
											// TODO Auto-generated method stub
											int videoOrArtId = ((Integer) v.getTag(R.id.id_tag)).intValue();
											ArticleBean bean = adapter.getChild(groupPosition, childPosition);
											if (bean != null && bean.getIsNew()) {
												ContentValues values = new ContentValues();
												values.put("_is_new", 0);
												int result = DbOperator.getInstance(MyApplication.getInstance()).updateData(ConstConfig.ARTICLE_TABLE, values, videoOrArtId);
												if (result > 0) {
													bean.setIsNew(false);
													adapter.notifyDataSetChanged();
												}
											}
											
											
											if (thirdBean.getId()==51) {
												//医学视频，调用播放器
												String jj=(String) v.getTag(R.id.video_url_tag);
												if (jj==null || "".equals(jj)) {
													return false;
												}
												
												try {
													jj=DES.decryptDES(jj, DES.KEY);
												} catch (Exception e1) {
													// TODO Auto-generated catch block
													e1.printStackTrace();
												}
												int divide=jj.lastIndexOf("/");
												String medium=jj.substring(0, divide+1);
												String videoName=jj.substring(divide+1);
												String[] videoPart=videoName.split("\\.");
												String enCodeName = null;
												try {
													//中文需进行utf-8编码
													enCodeName=URLEncoder.encode(videoPart[0], "UTF-8");
												} catch (UnsupportedEncodingException e) {
													// TODO Auto-generated catch block
													e.printStackTrace();
												}
												
												File dir=new File(ConstConfig.VIDEO_FILE_OUT);
												if (!dir.exists()) {
													boolean result= dir.mkdirs();
												 /**if (!result) {
														Toast.makeText(context, "请插入sd卡！", Toast.LENGTH_SHORT).show();
														return false;
													}*/
												}
												
												String fileName=null;
												File file=new File(dir, videoName);
												if (!file.exists()) {
													//内置存储卡上的视频文件
													file=new File(ConstConfig.VIDEO_FILE_INER, videoName);
													if (!file.exists()) {
														Toast.makeText(context, "找不到该视频文件！", Toast.LENGTH_SHORT).show();
														return false;
													}
													fileName=ConstConfig.VIDEO_FILE_INER + "/" + videoName;
												} else {
													fileName=ConstConfig.VIDEO_FILE_OUT + "/" + videoName;
												}
												
												String videoUrl=URLConfig.WEBSITE.substring(0, URLConfig.WEBSITE.length()-1)+medium+enCodeName+"."+videoPart[1];
												Intent videoIntent=new Intent(getActivity(),MyVideoPlayer.class);
												videoIntent.putExtra("url", videoUrl);
												videoIntent.putExtra("cache", fileName);
												startActivity(videoIntent);
												return false;
											}
											
											Intent intent=new Intent(getActivity(),ArticleActivity.class);
											intent.putExtra(ConstConfig.ID, videoOrArtId);
											startActivity(intent);
											return false;
										}
									});
									
									listView.setOnItemLongClickListener(new OnItemLongClickListener() {
										@Override
										public boolean onItemLongClick(AdapterView<?> arg0, final View v, int arg2, long arg3) {
											// TODO Auto-generated method stub
											DialogHelper.noticeDialog(context, null, new NoticeDialogCallback() {							
												@Override
												public void onClicked(int position) {
													// TODO Auto-generated method stub
													if (position==1) {
														int groupPosition=(Integer) v.getTag(R.id.group_position_tag);
														int artId=(Integer) v.getTag(R.id.id_tag);
														//type用来区别父item还是子item
														String type=(String) v.getTag(R.id.bean_tag);
														int row=-1;
														
														if (type!=null && !"".equals(type) && "art".equals(type)) {
															//父 item
															if (adapter.getDirList().size()<=0) {
																//没有group
																row=DbOperator.getInstance(context).deleteData(ConstConfig.ARTICLE_TABLE, artId);
																if (row>0) {
																	adapter.getArticleList().get(0).remove(groupPosition);
																}
															} else {
																//有group
																row=DbOperator.getInstance(context).deleteData(ConstConfig.ARTICLE_TABLE, artId);
																if (row>0) {
																	adapter.getArticleList().remove(groupPosition);
																	adapter.getDirList().remove(groupPosition);
																}
															}
														} else if (type==null) {
															//子item
															row=DbOperator.getInstance(context).deleteData(ConstConfig.ARTICLE_TABLE, artId);
															if (row>0) {
																int childPosition=(Integer) v.getTag(R.id.child_position_tag);
																adapter.getArticleList().get(groupPosition).remove(childPosition);
																if (thirdBean.getId()==51) {
																	//医学技术视频还需删除相关的视频文件
																	String jj=(String) v.getTag(R.id.video_url_tag);
																	if (jj!=null && !"".equals(jj)) {
																		try {
																			jj=DES.decryptDES(jj, DES.KEY);
																		} catch (Exception e1) {
																			// TODO Auto-generated catch block
																			e1.printStackTrace();
																		}
																		int divide=jj.lastIndexOf("/");
																		//获取视频名称
																		String videoName=jj.substring(divide+1);
																		//内置存储卡里面的文件
																		File file=new File(ConstConfig.VIDEO_FILE_INER,videoName);
																		if (file.exists()) {
																			//删除视频文件
																			file.delete();
																		}
																		file=new File(ConstConfig.VIDEO_FILE_OUT,videoName);
																		//外置存储卡里的视频文件能删则删
																		if (file.exists()) {
																			file.delete();
																		}
																	}
																}
															}
														}
														if (row>0) {
															adapter.notifyDataSetChanged();
															Toast.makeText(context, "删除成功！", Toast.LENGTH_SHORT).show();
														} else {
															Toast.makeText(context, "删除失败！", Toast.LENGTH_SHORT).show();
														}
													}
												}
											});
											return true;
										}
									});
									
									listView.setOnGroupClickListener(new OnGroupClickListener() {
										@Override
										public boolean onGroupClick(ExpandableListView parent, View v,
												int groupPosition, long id) {
											// TODO Auto-generated method stub
											String flag=(String) v.getTag(R.id.bean_tag);
											
											Serializable seria = adapter.getGroup(groupPosition);
											
											if ("art".equals(flag)) {
												//医学文章
												int articleId=((Integer) v.getTag(R.id.id_tag)).intValue();
												Intent intent=new Intent(getActivity(),ArticleActivity.class);
												intent.putExtra(ConstConfig.ID, articleId);
												startActivity(intent);
												
												//把该文章或视频的new标志清除掉
												ArticleBean bean = (ArticleBean) seria;
												if (bean != null && bean.getIsNew()) {
													ContentValues values = new ContentValues();
													values.put("_is_new", 0);
													int result = DbOperator.getInstance(MyApplication.getInstance()).updateData(ConstConfig.ARTICLE_TABLE, values, bean.getId());
													if (result > 0) {
														bean.setIsNew(false);
														adapter.notifyDataSetChanged();
													}
												}
											} else {
												//把该栏目的new标志清除掉
												KnowledgeBean bean = (KnowledgeBean) seria;
												if (bean != null && bean.getIsNew()) {
													ContentValues values = new ContentValues();
													values.put("_is_new", 0);
													int result = DbOperator.getInstance(MyApplication.getInstance()).updateData(ConstConfig.CATEGORT_TABLE, values, bean.getId());
													if (result > 0) {
														bean.setIsNew(false);
														adapter.notifyDataSetChanged();
													}
												}
											}
											//类型type包含kno和art两种
											String type=(String) v.getTag(R.id.bean_tag);
											if ("art".equals(type)) {
												//art为医学文章，已经没有继续展开的子项了
												//默认为false，设为true时，点击事件不会展开Group
												return true;
											}
											return false;
										}
									});
								}
								LoadingTip.hideDialog();
							}
						}, DbOperator.delayTime);
					}
				});
			}
		}.start();
	}
	
	
	
}
